<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use think\Cookie;

class Details extends Error
{ 
  /**
     * 显示指定资源列表
     *@param  int  $id
     * @return \think\Response
     */
    public function readbook($id)
    { 
      // 点击率 +1
      $hit = db('data')->where('id','=',$id)->setInc('hot');
     
      // 未登录|未购买 试读前三章
      !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
      if($uid){
        $status = db('orders')->where('cid',$id)->where('uid',$uid)->where('status',1)->find();
      }else{
        $status = null;
      }

        // 获取文章信息
        $data = db('article')->field(['id'])->where('cid',$id)->find();
        if (empty($data)) {  $id = 4; }
        $data = db('article')->field(['name,id'])->where('cid',$id)->order('id')->select();
        // status分支
        if ($status) {
          $list = db('article')->field('cid',true)->where('cid',$id)->paginate(1);
        }else{
          foreach ($data as $k => $v) { if ($k < 3) { $ids[] = $v['id'];} }
          $list = db('article')->field('cid',true)->where('cid',$id)->where('id','in',$ids)->paginate(1);
        }

       $page = $list->render();
       // 书本信息
       $book = db('data')->field(['id','name','author','price','face'])->where('id',$id)->find();

      return view('details/content',[
          'data'=>$data,
          'list'=>$list,
          'book'=>$book,
          'status'=>$status,
          'page'=>$page
        ]);
    }

   /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      // 书本信息
      $data = db('data')->where('id',$id)->find();
      // 分类信息
      $two = db('category')->field(['id','pid','name'])->where('id','=',$data['cid'])->find();
      $one = db('category')->field(['id','name'])->where('id','=',$two['pid'])->find();
      // 订单信息
      !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
      $info = db('orders')->where('cid',$id)->where('uid',$uid)->find();
      $vip = db('user')->where('id',$uid)->where('vip',1)->find();
      $this->assign('vip',$vip);
      if($info['status'] == 1){
         $info['dee'] = '已购买';
      }else{
         $info['dee'] = '购买全本';
      }
      // 目录信息
      $dir = db('article')->field('cid',true)->where('cid','=',$id)->select();
      $count_dir = count($dir);
        // 未登录|未购买 试读前三章
        if($uid){
          $status = db('orders')->where('cid',$id)->where('uid',$uid)->where('status',1)->find();
        }else{ $status = null; }
      // 评论信息
      $comment = db('comment')->where('cid','=',$id)->select();
        $arr = [];
        foreach ($comment as $k => $v) { $arr[] = $v['uid']; }
        $cmtUser = db('user')->field(['icon','name','id'])->where('id','in',$arr)->select();
        // user 与 comment 合并
         $score = ''; $array = [];
         foreach ($comment as $k => $v) { 
            $comment[$k]['icon'] = ''; $comment[$k]['name'] = '';
            foreach ($cmtUser as $k1 => $v1) {
              if ($v1['id'] == $v['uid']) {
                $comment[$k]['icon'] =$v1['icon'];
                $comment[$k]['name'] =$v1['name'];
              }
            } 
            $array[] = $v['cmt'];
           
         }
         // 将关联评论放在该评论下
          foreach ($comment as $k => $v) {
            if ($v['gid']!=null) {
                $son[] = $v;
                $comment = array_diff_key($comment,[$k=>'']);
            }
         }
        if (!empty($son)) {
          foreach ($comment as $k => $v) {
               $comment[$k]['son'] = [];
              foreach ($son as $k1 => $v1) {
                if ($v['id']==$v1['gid']) { $comment[$k]['son'][] = $v1; }
              }
            }
        }

       // 统计得分 评论条数
      if (!empty($array)) { $score = number_format(array_sum($array)*2/count($array),1); }else{ $score = '暂无'; }
      $count_cmt = count($comment);
      


      // 同类热门(一级)
        // 遍历二级分类池
        $child = db('category')->field(['id'])->where('pid','=',$two['pid'])->select();
        foreach ($child as $k => $v) { $child[$k] = $v['id']; }
        // 查询书本信息
        $hot = db('data')->field(['id','name','author','face','hot','price'])->where('cid','in',$child)
              ->where('id','neq',$data['id'])->order('hot desc')->limit(4)->select();
      // 相关推荐
        // $like = db('data')->field(['id','name','author','face','price'])->where('tag','like','%'.$data['tag'].'%')
        // ->where('id','neq',$data['id'])->limit(4)->select();
        $like = db('data')->field(['id','name','author','face','hot','price'])->where('cid','in',$child)
         ->where('id','neq',$data['id'])->order('id desc')->limit(4)->select();
     // 历史记录
       // 存为历史记录
       // session::set('book',null); die;
        session::set('book.'.$data['id'], $data);
        $books = session::get('book');
        // 保留5条(不包含当前)
        if (count(session::get('book')) > 6) {
           array_shift($books);
        }   
        session::set('book',$books);
        // 倒序
        $books = array_reverse($books);

      $this->assign('uid',$uid);
      $this->assign('data',$data);
      $this->assign('one',$one);
      $this->assign('two',$two);
      $this->assign('info',$info);
      $this->assign('dir',$dir);
      $this->assign('count_dir',$count_dir);
      $this->assign('comment',$comment);
      $this->assign('count_cmt',$count_cmt);
      $this->assign('score',$score);
      $this->assign('hotdata',$hot);
      $this->assign('likedata',$like);
      $this->assign('books',$books);
      $this->assign('title',$data['name'].'全文阅读');
      $this->assign('status',$status);

      return $this->fetch('details/index');
    }

  
    public function collect($id)
    {
        !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
         $data = [
            'uid'=>$uid,
            'cid'=>$id,
            'time'=>time()
        ];
        $res = Db::table('s75_collect')->where('cid',$id)->where('uid',$uid)->find();
        if($res){
                $info['status'] = 'false';
                $info['info'] = '你已经收藏过了';
        }else{
             $result = Db::table('s75_collect')->insert($data); 
              if($result>0) {
                $info['status'] = 'true';
                $info['info'] = '收藏成功';
              }else{
                $info['status'] = 'false';
                $info['info'] = '收藏失败';
              }
        }
        return json($info);
    }


    public function pay($id)
    {
       !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
       $res = Db::table('s75_data')->field(['price'])->where('id',$id)->find();
       $vip = db('user')->where('id',$uid)->where('vip',1)->find();
       if($vip){
          $info = [
            'uid'=>$uid,
            'cid'=>$id,
            'order_number'=>date('Ymdhis'),
            'status'=>'1',
            'otime'=>time(),
            'pay_money'=>$res['price']*0.7
         ];
       }else{
          $info = [
            'uid'=>$uid,
            'cid'=>$id,
            'order_number'=>date('Ymdhis'),
            'status'=>'1',
            'otime'=>time(),
            'pay_money'=>$res['price']
          ];
       }
       
       $result = Db::table('s75_orders')->where('cid',$id)->where('status',1)->where('uid',$uid)->find();
       if($result){
                $info['status'] = 'false';
                $info['info'] = '你已经购买过了';
       }else{
          $resul = Db::table('s75_orders')->where('cid',$id)->where('status',0)->where('uid',$uid)->find();
          if($resul){
          $inf = [
            'status'=>'1',
            'otime'=>time()
           ];
             $data = Db::table('s75_orders')->where('cid',$id)->update($inf);
             $info['status'] = 'true';
             $info['info'] = '购买成功';
          }else{
            $data = Db::table('s75_orders')->insert($info);
            $info['status'] = 'true';
            $info['info'] = '购买成功';
          }
         
       }
       return json($info);

       
    }

    public function buy($id)
    {
        !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
        $res1 = Db::table('s75_data')->field(['price'])->where('id',$id)->find();
        $vip = db('user')->where('id',$uid)->where('vip',1)->find();
        if($vip){
          $data = [
            'uid'=>$uid,
            'cid'=>$id,
            'order_number'=>date('Ymdhis'),
            'status'=>'0',
            'pay_money'=>$res1['price']*0.7,
            'otime'=>time()
            ];
        }else{
          $data = [
            'uid'=>$uid,
            'cid'=>$id,
            'order_number'=>date('Ymdhis'),
            'status'=>'0',
            'pay_money'=>$res1['price'],
            'otime'=>time()
            ];
        }
        $res = Db::table('s75_orders')->where('cid',$id)->where('uid',$uid)->find();
        if($res){
                $sta = Db::table('s75_orders')->where('cid',$id)->where('status',1)->where('uid',$uid)->find();
                if($sta){
                    $info['status'] = 'false';
                    $info['info'] = '你已购买过啦,不需要加入购物车';
                }else{
                    $info['status'] = 'false';
                    $info['info'] = '你已加入购物车';
                }
        }else{
              $result = Db::table('s75_orders')->insert($data); 
              if($result>0) {
                $info['status'] = 'true';
                $info['info'] = '加入购物车成功';
              }else{
                $info['status'] = 'false';
                $info['info'] = '加入购物车失败';
              }
        }
        return json($info);
    }
}
